<template>
	<view class="planpage">
	<!-- 	<view class="weekline">
			<view class="iconfont icon-xiangzuo"></view>
			<view class="week">
				08月01日-08月07日
			</view>
			<view class="iconfont icon-xiangyou2"></view>
		</view> -->
		
		
	
	<view class="box6x">
	        <view class="jieduanbox">
				<view class="jieduanline" v-for="(item,index) in detailData " :key="item.stageId">
					<view class="itemjieduan" v-for="(weekitem,index) in item.weeks " :key="weekitem.weekNo":class="jieduantab==weekitem.weekId?'jieduanact':''"  @click="selectjieduan(weekitem)">
						<view class="week">
							第{{weekitem.weekNo}}周
						</view>
						<view class="jieduan">
							{{item.stageTitle}}
						</view>
						
						<view class="jiao"></view>
					</view>
				</view>
			</view>
		     <view class="datebox">
		     	<view class="dateline"v-for="(item,index) in detailData " :key="item.stageId">
		     		<view class="itemdate" v-for="(weekitem,index) in item.weeks " :key="weekitem.weekNo" :class="timetab==weekitem.weekId?'dateact':''"  @click="selectjieduan(weekitem)">
		     			{{ formatToMonthDay(weekitem.startTime)}} - {{ formatToMonthDay(weekitem.endTime)}}
		     		</view>
		     	</view>
		     	
		     </view>
				
			</view>
  <view class="schedule-page">
	  	
    <!-- 左侧周几导航 -->
    <view class="left-nav">
      <view
        v-for="(day, index) in weekList.days"
        :key="index"
        :class="['nav-item', activeIndex === index ? 'active' : '']"
        @click="onLeftClick(index)"
      >
        <view class="weekday">{{ day.dayName }}</view>
        <view class="date">{{formatToMonthDay(day.dayDate) }}</view>
        <!-- <view class="mini-dots">
		   <view class="red"> </view>
		   <view class="blue"> </view>
		   <view class="green"> </view>
        </view> -->
      </view>
    </view>

    <!-- 右侧日程（可滚动） -->
    <scroll-view
      class="right-content"
      scroll-y
      :scroll-top="scrollTop"
      :scroll-into-view="scrollIntoId"
      @scroll="handleScroll"
      scroll-with-animation
    >
      <view
        v-for="(day, index) in weekList.days"
        :key="index"
        :id="'day' + index"
        class="day-block"
      >
      <!--  <view class="day-title">{{ day.week }} · {{ day.date }}</view> -->

        <!-- 每天的多个时间任务 -->
        <view
          v-for="(item, i) in day.tasks"
          :key="i"
          class="timeline-item"
        >
          <view class="time">{{ item.taskTime }}</view>
          <view class="timeline-dot" ></view>
          <view class="card" >
            <view class="card-title">{{ item.taskTitle }}</view>
            <view class="card-desc">{{ item.taskContent }}</view>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
  </view>
</template>

<script>
	
	import{changbanServiceInfo} from '../../utils/api.js'
export default {
  data() {
    return {
      jieduantab:'',
	  timetab:'',
      scrollIntoId: "",
      scrollTop: 0,
      offsets: [], // 每个 day-block 的起始偏移（滚动内容内）
      lastScrollTs: 0,
      weekList: [
        {
          week: "周一",
          date: "08.03",
          dots: ["#ff4d4f", "#52c41a"],
          list: [
            { time: "09:25", title: "随访签到", desc: "这里是随访签到的详细内容", type: "blue" },
            { time: "10:00", title: "测体温", desc: "量体温并记录", type: "green" },
            { time: "14:30", title: "康复训练A", desc: "康复训练说明", type: "orange" },
			 { time: "15:30", title: "康复训练A", desc: "康复训练说明", type: "orange" },
			  { time: "16:30", title: "康复训练A", desc: "康复训练说明", type: "orange" },
			   { time: "17:30", title: "康复训练A", desc: "康复训练说明", type: "orange" }
          ]
        },
        {
          week: "周二",
          date: "08.04",
          dots: ["#1890ff"],
          list: [
            { time: "09:45", title: "运动处方A1", desc: "运动处方A1内容", type: "orange" },
			 { time: "09:55", title: "运动处方A1", desc: "运动处方A1内容", type: "orange" },
			  { time: "10:45", title: "运动处方A1", desc: "运动处方A1内容", type: "orange" },
			   { time: "11:45", title: "运动处方A1", desc: "运动处方A1内容", type: "orange" },
            { time: "15:00", title: "营养咨询", desc: "营养师面谈", type: "green" }
          ]
        },
        {
          week: "周三",
          date: "08.05",
          dots: ["#52c41a", "#722ed1"],
          list: [
            { time: "09:55", title: "进食窗口", desc: "记录进食情况", type: "green" },
			{ time: "10:45", title: "运动处方A1", desc: "运动处方A1内容", type: "orange" },
			 { time: "11:45", title: "运动处方A1", desc: "运动处方A1内容", type: "orange" },
            { time: "11:50", title: "血糖检测", desc: "空腹与餐后检测", type: "blue" },
            { time: "16:30", title: "心理辅导", desc: "小组心理辅导", type: "purple" }
          ]
        },
		{
		  week: "周四",
		  date: "08.05",
		  dots: ["#52c41a", "#722ed1"],
		  list: [
		    { time: "09:55", title: "进食窗口", desc: "记录进食情况", type: "green" },
			{ time: "10:45", title: "运动处方A1", desc: "运动处方A1内容", type: "orange" },
			 { time: "11:45", title: "运动处方A1", desc: "运动处方A1内容", type: "orange" },
		    { time: "11:50", title: "血糖检测", desc: "空腹与餐后检测", type: "blue" },
		    { time: "16:30", title: "心理辅导", desc: "小组心理辅导", type: "purple" }
		  ]
		},
		{
		  week: "周五",
		  date: "08.05",
		  dots: ["#52c41a", "#722ed1"],
		  list: [
		    { time: "09:55", title: "进食窗口", desc: "记录进食情况", type: "green" },
			{ time: "10:45", title: "运动处方A1", desc: "运动处方A1内容", type: "orange" },
			 { time: "11:45", title: "运动处方A1", desc: "运动处方A1内容", type: "orange" },
		    { time: "11:50", title: "血糖检测", desc: "空腹与餐后检测", type: "blue" },
		    { time: "16:30", title: "心理辅导", desc: "小组心理辅导", type: "purple" }
		  ]
		},
		{
		  week: "周六",
		  date: "08.05",
		  dots: ["#52c41a", "#722ed1"],
		  list: [
		    { time: "09:55", title: "进食窗口", desc: "记录进食情况", type: "green" },
			{ time: "10:45", title: "运动处方A1", desc: "运动处方A1内容", type: "orange" },
			 { time: "11:45", title: "运动处方A1", desc: "运动处方A1内容", type: "orange" },
		    { time: "11:50", title: "血糖检测", desc: "空腹与餐后检测", type: "blue" },
		    { time: "16:30", title: "心理辅导", desc: "小组心理辅导", type: "purple" }
		  ]
		},
		{
		  week: "周日",
		  date: "08.05",
		  dots: ["#52c41a", "#722ed1"],
		  list: [
		    { time: "09:55", title: "进食窗口", desc: "记录进食情况", type: "green" },
			{ time: "10:45", title: "运动处方A1", desc: "运动处方A1内容", type: "orange" },
			 { time: "11:45", title: "运动处方A1", desc: "运动处方A1内容", type: "orange" },
		    { time: "11:50", title: "血糖检测", desc: "空腹与餐后检测", type: "blue" },
		    { time: "16:30", title: "心理辅导", desc: "小组心理辅导", type: "purple" }
		  ]
		},
        // ... 其余天
      ],
	  sid:'',
	  detailData:[],
	  activeIndex:''
    };
  },
  onLoad(e) {
     this.sid=e.sid
  },
  onShow() {
  	
  	let p={
  		phone:uni.getStorageSync('phone'),
  		serviceId:this.sid
  	}
  	changbanServiceInfo(p).then(res=>{
  		console.log(res)
		 const list = res.data.data;
		
		        // 组装成树形结构
		        const stagesMap = new Map();
		
		        list.forEach(item => {
		          if (!item.stageId) return;
		
		          let stage = stagesMap.get(item.stageId);
		          if (!stage) {
		            stage = {
		              stageId: item.stageId,
		              stageNo: item.psStageNo,
		              stageTitle: item.psStageTitle,
		              startTime: item.psStartTime,
		              endTime: item.psEndTime,
		              weeks: new Map()
		            };
		            stagesMap.set(item.stageId, stage);
		          }
		
		          if (item.weekId) {
		            let week = stage.weeks.get(item.weekId);
		            if (!week) {
		              week = {
		                weekId: item.weekId,
		                weekNo: item.weekNo,
		                weekName: item.weekName,
		                startTime: item.pwStartTime,
		                endTime: item.pwEndTime,
		                days: new Map()
		              };
		              stage.weeks.set(item.weekId, week);
		            }
		
		            if (item.dayId) {
		              let day = week.days.get(item.dayId);
		              if (!day) {
		                day = {
		                  dayId: item.dayId,
		                  dayNo: item.dayNo,
		                  dayName: item.dayName,
		                  dayDate: item.dayDate,
		                  tasks: []
		                };
		                week.days.set(item.dayId, day);
		              }
		
		              if (item.taskId) {
		                day.tasks.push({
		                  taskId: item.taskId,
		                  taskTitle: item.taskTitle,
		                  taskContent: item.taskContent,
		                  taskTime: item.taskTime
		                });
		              }
		            }
		          }
		        });
		        // 转为普通数组
		        this.detailData = Array.from(stagesMap.values()).map(stage => ({
		          ...stage,
		          weeks: Array.from(stage.weeks.values()).map(week => ({
		            ...week,
		            days: Array.from(week.days.values())
		          }))
		        }));
		      
			this.$nextTick(() => {
				 console.log(this.detailData,'000000000')
			  this.jieduantab=this.detailData[0]?.weeks[0].weekId
			   this.timetab=this.detailData[0]?.weeks[0].weekId
			  this.weekList = this.detailData && this.detailData[0] && this.detailData[0].weeks && this.detailData[0].weeks[0] || []
			   console.log(this.jieduantab,'000000000')
			})
			 
			   
  	})
	
  },
  mounted() {
    // 等渲染完成后计算每个 day-block 的偏移（基于高度累加）
    this.$nextTick(() => {
      this.calculateOffsets();
      // 如果你的内容里有图片或异步内容，需在图片加载后再次调用 calculateOffsets()
    });
  },
  methods: {
	  
	  selectjieduan(e){
		  console.log(e)
		  this.jieduantab=e.weekId
		  this.timetab=e.weekId
		  this.weekList=e
	  },
	  formatToMonthDay(dateStr) {
	    // 兼容 iOS 的写法，最好把 T 换成空格
	    let d = new Date(dateStr.replace('T', ' ').replace(/-/g, '/'))
	    let m = d.getMonth() + 1
	    let day = d.getDate()
	    return `${m}月${day}日`
	  },

    // 点击左侧某天，跳转右侧对应区块
    onLeftClick(index) {
		console.log(index,'000')
      this.activeIndex = index;
      // 使用 scroll-into-view 跳转
      this.scrollIntoId = "day" + index;
      // 清掉 scrollIntoId（可选），避免后续干扰
      setTimeout(() => {
        this.scrollIntoId = "";
      }, 400);
    },

    // 计算每个 day-block 的起始偏移（基于高度累加）
    calculateOffsets() {
      const query = uni.createSelectorQuery().in(this);
      query.selectAll(".day-block").boundingClientRect();
      query.exec((res) => {
        if (!res || !res[0]) return;
        const rects = res[0]; // 每个 day-block 的 rect（含 height）
        const offsets = [];
        let sum = 0;
        for (let i = 0; i < rects.length; i++) {
          offsets.push(sum);
          sum += rects[i].height;
        }
        this.offsets = offsets;
        // 可选：把最后一个索引的 end 设为 sum，方便计算
        this.totalHeight = sum;
      });
    },

    // 右侧滚动处理（带简单节流）
    handleScroll(e) {
      const now = Date.now();
      if (now - this.lastScrollTs < 80) return; // 80ms 节流
      this.lastScrollTs = now;

      const scrollTop = e.detail.scrollTop || 0;
      // 找到 offsets 中对应的 index
      let idx = 0;
      for (let i = 0; i < this.offsets.length; i++) {
        const start = this.offsets[i];
        const end = i + 1 < this.offsets.length ? this.offsets[i + 1] : this.totalHeight + 1;
        if (scrollTop >= start && scrollTop < end) {
          idx = i;
          break;
        }
      }
      if (this.activeIndex !== idx) {
        this.activeIndex = idx;
      }
    }
  },
  watch: {
    // 如果 weekList 变了（异步加载数据），重新计算偏移
    weekList: {
      handler() {
        this.$nextTick(() => {
          this.calculateOffsets();
        });
      },
      deep: true
    }
  }
};
</script>

<style lang="less" scoped>
	.planpage{
		width: 750rpx;
		box-sizing: border-box;
		height: 100vh;
	}
.schedule-page {
  display: flex;
  height: 90vh;
  overflow-y: auto;
  background: #f5f7fb;
}
		.weekline{
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 40rpx 0;
			background-color: white;
			.week{
				margin: 0 30rpx;
				font-weight: bold;
				color: #1A4F8A;
				font-size: 32rpx;
				font-family: OPPOSans-black;
			}
			.iconfont{
				color: #1A4f8a;
			}
		}
		
.box6x{
	  	width: 100%;
	  
	  	margin-top: 10rpx;
	  	box-sizing: border-box;
	  	background: white;
		.jieduanbox{
			width: 100%;
			box-sizing: border-box;
			padding: 10rpx 20rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			overflow-x: auto;
			
		}

	  	.jieduanline{
	  		width: 100%;
			min-width: 400rpx;
	  		margin-top: 20rpx;
	  		height: 200rpx;
	  		display: flex;
	  		align-items: center;
	  		overflow-x: auto;
	  		flex-wrap: nowrap; /* 禁止换行 */
	  					
	  		scrollbar-width: none;
	  					 -webkit-overflow-scrolling: touch; /* iOS平滑滚动 */
	  					 /* 隐藏所有滚动条 */
	  					 ::-webkit-scrollbar {
	  					   display: none;
	  					   width: 0;
	  					   height: 0;
	  					   color: transparent;
	  					 }
	  		
	  		.itemjieduan{
	  			width: 180rpx;
	  			min-width: 150rpx;
	  			margin: 0 20rpx;
	  			height: 180rpx;
	  			border-radius: 20rpx;
	  			box-sizing: border-box;
	  			position: relative;
	  			padding-top: 50rpx;
	  			padding-left: 20rpx;
	  			 box-shadow: 
	  			    5px 0 10px -5px rgba(0,0,0,0.2),  /* 左侧阴影 */
	  			    -5px 0 10px -5px rgba(0,0,0,0.2), /* 右侧阴影 */
	  			    0 5px 10px -5px rgba(0,0,0,0.2);  /* 底部阴影 */
	  			.week{
	  				width: 100rpx;
	  				height: 36rpx;
	  				position: absolute;
	  				color: #E6E6E6 ;
	  				font-size: 26rpx;
	  				text-align: center;
	  				line-height: 36rpx;
	  				font-weight: bold;
	  				right: 0;
	  				top: 0;
	  				border-top-right-radius: 20rpx;
	  				border-bottom-left-radius: 20rpx;
	  			}
	  			.jieduan{
	  				font-weight: bold;
	                   font-size: 26rpx;
	  				 color: #858585;			 
	  			}
	  			.jieduantitle{
	  				 color: #858585;	
	  				 font-weight: bold;
	  			}
	  		}
	  		.jieduanact{
	  			 background: linear-gradient(180deg, rgba(26,79,138,1) 0%,rgba(26,79,138,0.5) 100%);
	  			.week{
	  				 background: linear-gradient(180deg, rgba(26,79,138,1) 0%,rgba(255,255,255,0.3) 100%);
	  				color: white;
	  			}
	  			.jieduan{
	  				color: white;
	  			}
	  			.jieduantitle{
	  				color: white;
	  			}
	  			.jiao{
	  				position: absolute;
	  				width: 24rpx;
	  				height: 24rpx;
	  				background-color: #DECFFF ;
	  				bottom: -10rpx;
	  				z-index: -1;
	  				left: 65rpx;
	  				rotate: 45deg;
	  			}
	  		}
	  	}
		.datebox{
			width: 100%;
			display: flex;
			align-items: center;
			overflow-x: auto;
			padding: 14rpx 0;
		}
	  	.dateline{
	  		width: 100%;
			min-width: 600rpx;
	  		display: flex;
	  		align-items: center;
	  		overflow-x: auto;
	  		padding: 14rpx 0;
	  		.itemdate{
	  			padding: 10rpx;
	  			color: #C3C3C3 ;
	  			width: 260rpx;
	  			min-width: 300rpx;
	  			font-size: 28rpx;
	  			box-sizing: border-box;
	  			border-radius: 22rpx;
	  			background-color: whitesmoke;
	  			margin: 0 10rpx;
	  		}
	  		.dateact{
	  			background-color: rgba(255,253,248,1);
	  			border: 1px solid #1A4F8A ;
	  			color:#1A4F8A ;
	  			font-weight: bold;
	  		}
	  	}
	  	
	  }
/* 左侧 */
.left-nav {
  width: 180rpx;
  background: #f0f2f5;
  height: 70vh;
  box-sizing: border-box;
}
.nav-item {
  padding: 20rpx;
  text-align: center;
line-height: 2.2;
}

.weekday { font-size: 30rpx; color: #333; }
.date { font-size: 26rpx; color: #999;  }
.mini-dots { margin-top: 6rpx; display:flex; justify-content:space-evenly;  }
.red { width:10rpx; height:10rpx; border-radius:50%;background-color: red; }
.blue { width:10rpx; height:10rpx; border-radius:50%;background-color: #0099ff; }
.green { width:10rpx; height:10rpx; border-radius:50%; background-color: greenyellow;}
.nav-item.active {
 
  color: #0099ff !important;
  font-weight: 600;
  .weekday { font-size: 30rpx; color: #0099ff !important; }
  .date { font-size: 26rpx;  color: #0099ff !important;}
}
/* 右侧 */
.right-content {
  flex: 1;
  padding: 20rpx;
  box-sizing: border-box;
  background: #fff;
  overflow-y: auto;
}
.day-block {
  padding-bottom: 30rpx;
  border-bottom: 20rpx solid transparent;
}
.day-title {
  font-weight: bold;
  margin-bottom: 18rpx;
  color: #333;
}
.timeline-item {
  display: flex;
  align-items: flex-start;
  margin-bottom: 18rpx;
}
.time {
  width: 120rpx;
  font-weight: bold;
  font-size: 28rpx;

}
.timeline-dot {
  width: 18rpx;
  height: 18rpx;
  border-radius: 50%;
  margin-right: 14rpx;
  margin-top: 8rpx;
  background: #bbb;
}
.card {
  flex: 1;
  min-height: 100rpx;
  padding: 18rpx;
  border-radius: 12rpx;
  background: #f2f8ff;
  box-sizing: border-box;
}
.card-title { font-weight: 600; padding: 10rpx; }
.card-desc { color: #666; font-size: 24rpx; }

/* 类型颜色示例 */
.card.blue { background: #e8f5ff; }

.card.green { background: #f0fff0; }

.card.orange { background: #fff7e6; }

.card.purple { background: #faf0ff; }

</style>
